import type { RouteLocationNormalizedLoaded, Router } from 'vue-router'
import { useRoute } from 'vue-router'
import { defineStore } from 'pinia'

export interface TagsViewState {
  breadcrumbDic: { [key: string]: Array<AppRouteRecordRaw> } // 非菜单类面包屑路由层级字典
}

export const useBreadcrumbStore = defineStore('breadcrumb', {
  state: (): TagsViewState => ({
    breadcrumbDic: {}
  }),
  actions: {
    // 存储面包屑字典，多级导航情况下，目标路由即上一级路由需要调此方法，eg：pushBreadcrumbDic(target, route) > pushBreadcrumbDic(route.path, route, true)
    pushBreadcrumbDic(targetPath: string, route: RouteLocationNormalizedLoaded, isEnd = false) {
      if (!this.breadcrumbDic[targetPath]) {
        this.breadcrumbDic[targetPath] = []
      }

      const pushRoute: AppRouteRecordRaw = {
        name: route.name as string,
        path: route.path,
        meta: {
          icon: route.meta.icon,
          title: route.meta.title
        }
      }

      if (isEnd) {
        if (
          !this.breadcrumbDic[targetPath].length ||
          this.breadcrumbDic[targetPath][this.breadcrumbDic[targetPath].length - 1].path !==
            targetPath
        ) {
          this.breadcrumbDic[targetPath].push(pushRoute)
        }
      } else {
        this.breadcrumbDic[targetPath] = this.breadcrumbDic[route.path]
          ? [...this.breadcrumbDic[route.path]]
          : [pushRoute]
      }
    },
    // 快速构建，注意：在非onMounted阶段需要传router
    buildBreadcrumbDic(targetPath?: string, router?: Router) {
      // 如果存在targetPath，表示处于面包屑中间层级
      if (targetPath) {
        if (router) {
          this.pushBreadcrumbDic(targetPath, router.currentRoute.value)
          router.push(targetPath)
        }
      } else {
        const route = useRoute()
        this.pushBreadcrumbDic(route.path, route, true)
      }
    }
  }
})

export const breadcrumbStore = useBreadcrumbStore()
